package com.zhan.signalling.data.listener;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import com.zhan.signalling.commons.Constants;
import com.zhan.signalling.commons.SocketEvent;
import com.zhan.signalling.message.AccoutType;
import com.zhan.signalling.message.Message;
import com.zhan.signalling.message.Result;
import com.zhan.signalling.server.SocketServer;

/**
 * 动态创建namespace 只有超级管理员有权限
 * @author knight
 *
 */
public class CreatePlatformListener implements DataListener<Message> {
	
	private static Logger log = LoggerFactory.getLogger(CreatePlatformListener.class);
	
	public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
		
		Integer status = Constants.SUCCESS;
		String content = null;
		try {
			Integer accoutType = client.get(Constants.USER_TYPE);
			String platform = data.getPlatform();
			if(StringUtils.isNotBlank(platform)) {
				//超管能操作
				if(AccoutType.ADMIN.getType().equals(accoutType)) {
					if(SocketServer.namespaceList.contains(platform)) {
						content = "platform is exist";
						status = Constants.FAILED;
					}
					content = "create platform success";
					//添加namespace　并绑定事件
					SocketServer.addNameSpace(platform);
					log.info("create "+platform+" platform success");
				}else {
					status = Constants.FAILED;
					content = "not permission";
				}
			}else {
				// 不能创建null
				status = Constants.FAILED;
				content = "platform is null";
			}
			client.sendEvent(SocketEvent.CHAT_EVENT, new Result(content, status));
		} catch (Exception e) {
			log.error(e.getMessage());
			client.sendEvent(SocketEvent.CHAT_EVENT, new Result("create platform failed", Constants.FAILED));
		}
	}
}
